//
//  NetworkingTools.swift
//  3-封装AFN-swift
//
//  Created by yellow on 15/10/16.
//  Copyright © 2015年 yellow. All rights reserved.
//

import UIKit
import AFNetworking


//定义枚举，需要指定枚举的类型(类型可以使任何类型)
//enum HttpMethod:String{
//    case GET = "GET"
//    case POST = "POST"
//}
//
////定义成功和失败的闭包,并重定义
//typealias SuccessBlock = ((NSURLSessionDataTask, AnyObject) -> (Void))?
//typealias FailureBlock = ((NSURLSessionDataTask, NSError) -> (Void))?

class NetworkingTools: NSObject,NetworkingProtocol{
    static let manager = NetworkingTools()
    /// manager持有AFHTTPSessionManager的引用
    private var sessionManager:AFHTTPSessionManager?
    
    override init() {
        self.sessionManager = AFHTTPSessionManager(baseURL: nil)
//        self.sessionManager?.responseSerializer = AFHTTPResponseSerializer()//二进制解析器
        
        // 设置反序列化数据格式 - 系统会自动将 OC 框架中的 NSSet 转换成 Set
        self.sessionManager?.responseSerializer.acceptableContentTypes?.insert("text/plain")
        super.init()
    }
    
    
}

extension NetworkingTools{
    
    /// 文件上传,name参数是server需要接受该数据的key
    func httpUpload(fileData:NSData,name:String,URLString:String,parameter:AnyObject?,finished:FinishedBlock){
        sessionManager?.POST(URLString, parameters: parameter, constructingBodyWithBlock: { (formData) -> Void in
            
            formData.appendPartWithFileData(fileData, name: name, fileName: "anyName", mimeType: "application/octet-stream")
            
            }, success: { (_, result) -> Void in
                finished!(result: result, error: nil)
            }, failure: { (_, error) -> Void in
                print(error)
                finished!(result: nil, error: error)
        })
        
    }

    
    
    /// 普通请求 GET POST
    func httpRequest(httpMethod:HttpMethod,URLString:String,parameter:AnyObject?,finished:FinishedBlock){
        
        var success:((task:NSURLSessionDataTask,result: AnyObject) -> (Void))?
        var failure:((task:NSURLSessionDataTask,error: NSError) -> (Void))?
        if let finishedBlock = finished {
            // TODO: 模拟网络延迟
            success = {(task:NSURLSessionDataTask,result: AnyObject) -> (Void)
                in
                finishedBlock(result: result,error: nil)
            }
            failure = {(task:NSURLSessionDataTask,error: NSError) -> (Void)
                in
                finishedBlock(result: nil,error: error)
            }
        }else{
            success = nil
            failure = nil
        }
        
        
        if httpMethod == .GET {
            sessionManager?.GET(URLString, parameters: parameter, success: success, failure: failure)
        }else{
            sessionManager?.POST(URLString, parameters: parameter, success: success, failure: failure)
        }
    }
}

